package javaTest04.exercise01.processor;

import javaTest04.entity.Person;
import javaTest04.exercise01.annotation.Label;

import java.lang.reflect.Field;
import java.util.Scanner;

public class PersonInput implements PersonAction {
    @Override
    public Person process(Person person) {
        input(
                new Scanner(System.in),
                person.getClass().getDeclaredFields(),
                person.getClass().getAnnotation(Label.class),
                person
        );
        return person;
    }

    private void input(Scanner in, Field[] fields, Label personLabel, Object person) {//录入信息
        System.out.println("接下来请输入" + personLabel.value() + "相关信息:");
        for (Field field : fields) {
            field.setAccessible(true);//设置成可访问
            Label fieldLabel = field.getAnnotation(Label.class);
            System.out.print("请输入" + fieldLabel.value() + ":");
            setFieldValue(field, in.next(), person);
        }
    }

    private void setFieldValue(Field field, String info, Object obj) {//判断字段类型
        try {
            switch (field.getType().getSimpleName()) {
                case "Integer":
                    field.set(obj, Integer.parseInt(info));
                    break;
                case "String":
                    field.set(obj, info);
                    break;
                case "Boolean":
                    field.set(obj, Boolean.parseBoolean(info));
                    break;
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

}
